import { Body, Get, Inject, Post } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { DeviceDeviceEntity } from '../../entity/device';
import { DeviceDeviceService } from '../../service/device';
import { Context } from '@midwayjs/koa';
import { UserInfoService } from '../../../user/service/info';

/**
 * 设备信息
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: DeviceDeviceEntity,
  service: DeviceDeviceService,
  // 向表插入当前登录用户ID
  insertParam: ctx => {
    return {
      userId: ctx.user.id,
    };
  },
  pageQueryOp: {
    keyWordLikeFields: ['a.deviceNo'],
    fieldEq: ['a.deviceType', 'a.deviceStatus'],
    where: async ctx => {
      const conditions = [];
      const userInfoService = await ctx.requestContext.getAsync(
        UserInfoService
      );
      const user = await userInfoService.person(ctx.user.id);

      // 1: 代理, 2: 商户, 3: 平台
      // 如果是代理
      if (user && user.role === 1) {
        conditions.push(['a.agentId = :agentId', { agentId: user.id }]);
      }
      // 如果是商户
      else if (user && user.role === 2) {
        conditions.push(['a.userId = :userId', { userId: user.id }]);
      }



      // 检查用户角色，如果不是平台角色（例如 role !== 3），则添加过滤条件
      // if (user && user.role !== 3) {
      //   // 假设 role 0 是平台管理员
      //   conditions.push(['a.userId = :userId', { userId: ctx.user.id }]);
      // }
      return conditions;
    },
  },
})
export class AppDeviceDeviceController extends BaseController {
  @Inject()
  deviceDeviceService: DeviceDeviceService;

  @Inject()
  ctx: Context;

  @Post('/addDevice')
  async addDevice(
    // 设备号
    @Body('deviceNo') deviceNo: string
  ) {
    return this.ok(
      await this.deviceDeviceService.addDevice({
        deviceNo: deviceNo,
        userId: this.ctx.user.id,
      })
    );
  }

  // 删除设备
  @Post('/unbindDevice')
  async unbindDevice(
    // 设备号
    @Body('deviceNo') deviceNo: string
  ) {
    return this.ok(await this.deviceDeviceService.unbindDevice({
      deviceNo: deviceNo,
      userId: this.ctx.user.id,
    }));
  }

  // 获取设备列表
  @Post('/getDeviceCount')
  async getDeviceList() {
    return this.ok(await this.deviceDeviceService.getDeviceCount());
  }
}
